﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project2.容器
{
    internal class MyStack<T> : IEnumerable<T>
    {
        private int _size;
        private T[] _items;
        private int _version;

        public MyStack()
        {
            _items = new T[10];
            _size = 0;
            _version = 0;
        }

        public MyStack(int initialCapacity)
        {
            if (initialCapacity < 0)
            {
                throw new Exception("initialCapacity不能为0");
            }

            if (initialCapacity < 10)
            {
                initialCapacity = 10;
            }

            _items = new T[initialCapacity];
            _size = 0;
            _version = 0;
        }

        public void Push(T item)
        {
            if (_size == _items.Length)
            {
                T[] newItems = new T[_items.Length * 2];
                Array.Copy(_items, 0, newItems, 0, _size);
                _items = newItems;
            }
            _items[_size++] = item;
            _version++;
        }

        public T Pop()
        {
            if (_size == 0)
            {
                throw new Exception("栈空");
            }

            _size--;
            T result = _items[_size];
            _items[_size] = (T)default;
            _version++;

            return result;
        }

        public T Peek()
        {
            if (_size == 0)
            {
                throw new Exception("栈空");
            }
            return _items[_size - 1];
        }

        public void Clear()
        {
            Array.Clear(_items, 0, _size);
            _size = 0;
            _version++;
        }

        public int Count
        {
            get { return _size; }
        }

        /// <summary>
        /// 迭代器，用于foreach迭代
        /// </summary>
        /// <returns></returns>
        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 0; i < _size; i++)
            {
                if (_items[i] != null)
                {
                    yield return _items[i];
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}